﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;
using System.Collections;
using System.Web;
using System.Data;

namespace SIMSProject.Common
{
    class Common
    {
        
        public static void SendEmail(SPWeb web, string to, string cc, string subject, string content)
        {
            try
            {
                if (!SPUtility.IsEmailServerSet(web))
                {
                    return;
                }

                if ((to == null || to.Trim() == string.Empty) && (cc == null || cc.Trim() == string.Empty))
                {
                    return;
                }


                content = content.Replace("<br>", "<br>\n");
                content = content.Replace("<br />", "<br />\n");
                content = content.Replace("<br/>", "<br/>\n");

                string fromAddress = web.CurrentUser.Email;
                if (string.IsNullOrEmpty(fromAddress))
                {
                    fromAddress = web.Site.WebApplication.OutboundMailSenderAddress;
                }

                var headers = new StringDictionary();
                headers.Add("from", fromAddress);
                headers.Add("to", to);
                headers.Add("cc", cc);
                headers.Add("subject", subject);
                headers.Add("content-type", "text/html");
                SPUtility.SendEmail(web, headers, content);
            }
            catch (Exception ex)
            {
                
            }
        }

        public static String GetEmailAddressesFromName(String name) 
        {
          StringBuilder resolvedAddresses = new StringBuilder();
          
            SPSite siteColl = SPContext.Current.Site;
            SPWeb site = SPContext.Current.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
                    {
                        IEnumerable addresses = getEmailAddressesFromName(name, ElevatedSite);
                        foreach (string address in addresses)
                        {
                            if (!String.IsNullOrEmpty(address))
                            {
                                resolvedAddresses.AppendFormat("{0};", address);
                            }
                        }
                        
                    }
                }
            });
            return resolvedAddresses.ToString();
        }

        public static void GenerateOrderPrint(SPItem item,DataTable dt)
        {
            string dateCreate = DateTime.Now.ToShortDateString();
            string customerName = item[Constant.Order.CustomerName].ToString();
            string customerPhone = item[Constant.Order.CustomerPhone].ToString();
            string customerAddress = item[Constant.Order.CustomerAddress].ToString();
            string customerTaxCode = item[Constant.Order.TaxCode].ToString();

            string tableContent = string.Empty;
            Int64 total =0;

            int i = 1;
            if(dt!=null)
                foreach (DataRow dr in dt.Rows)
                {
                    tableContent += "<tr>";
                    tableContent += "<td>" + i + "</td>";
                    tableContent += "<td>" + dr["ProductCode"] + "</td>";
                    tableContent += "<td>" + dr["ProductName"] + "</td>";
                    tableContent += "<td>" + dr["ProductUnitType"] + "</td>";
                    tableContent += "<td>" + dr["Quantity"] + "</td>";
                    tableContent += "<td>" + dr["ProductPrice"] + "</td>";

                    int price = 0;
                    int.TryParse(dr["ProductPrice"].ToString(),out price);
                    int quantity = 0;
                    int.TryParse(dr["Quantity"].ToString(), out quantity);

                    Int64 lineTotal = price * quantity;
                    tableContent += "<td>" + lineTotal + "</td>";
                    tableContent += "</tr>";
                    i++;
                    total += lineTotal;
                }

            //Creating HttpContext
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.ContentType = "application/msword";

            //File name for the exported word document
            string strFileName = "[SIMS][Order]"+ item[Constant.Order.OrderCode] + ".doc";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
            
            //Giving heading to the Word Document with style
            StringBuilder strHTMLContent = new StringBuilder();
            strHTMLContent.Append(@"<div style='width:1000px;margin:auto'>
                                    <h3>Xí nghiệp thuốc thú y Trung Ương - Vetvaco</h3>
                                    <h5>MST: ............</h5>
                                    <hr>
                                    <center><h1>HÓA ĐƠN BÁN HÀNG</h1>
                                    Ngày lập phiếu :"+dateCreate+@"
                                    <br/>
                                    Số:
                                    </center>
                                    <br>
                                    <b>Tên Khách Hàng:</b>"+customerName+@"<br>
                                    <b>Địa chỉ:</b>" + customerAddress + @"<br>
                                    <b>Điện thoại:</b>" + customerPhone + @"<br>
                                    <b>Mã số thuế:</b>" + customerTaxCode + @"<br>
                                    <b>Ghi chú : </b>
                                    <br/>
                                    <table border='1'>
                                    <tbody><tr>
                                    <th width='40'>STT</th>
                                    <th width='100'>Mã Hàng</th>
                                    <th width='300'>Tên Hàng</th>
                                    <th width='100'>Đơn vị</th>
                                    <th width='160'>Số lượng</th>
                                    <th width='200'>Đơn giá</th>
                                    <th width='300'>Thành tiền</th>
                                    </tr>
                                    " + tableContent + @"
                                    </tbody></table>
                                    <br/>
                                    <br/>
                                    Tổng tiền hàng :
                                    " + total + @"VND
                                    <br/>
                                    Bằng chữ :
                                    <br/>
                                    <br/>
                                    <table width='100%'>
                                    <tr>
	                                    <td><b>Người nhận</b></td>
	                                    <td><b>Thủ kho</b></td>
	                                    <td><b>Kế toán</b></td>
                                    </tr>
                                    </table>
                                    </div>");
            
            ////Looping through each list item in  the list
            //foreach (SPListItem oListItem in collListItems)
            //{
            //    strHTMLContent.Append("<tr><td>" + oListItem["Choice_Field_Name"].ToString() + "</td></tr>");
            //}

            strHTMLContent.Append("</table>".ToString());
            strHTMLContent.Append("<br><br>".ToString());
            HttpContext.Current.Response.Write(strHTMLContent);
            HttpContext.Current.Response.End();
            HttpContext.Current.Response.Flush();
        }

        private static IEnumerable<string> getEmailAddressesFromName(string name,SPWeb web) 
        {
            SPGroup group = getGroup(name,web);
            if (group != null) 
            {        
               return getEmailAddressesFromGroup(group);
            }
            SPUser user = getUser(name,web);
            if (user != null) {       
                return new string[] {user.Email};
            }
            return new string[0];
        }

        private static IEnumerable<string> getEmailAddressesFromGroup(SPGroup group)
        {
          List<string> addresses = new List<String>();
          foreach (SPUser user in group.Users) {
            addresses.Add(user.Email);
          }
          return addresses;
        }

        private static SPGroup getGroup(string name,SPWeb web) 
        {
          foreach (SPGroup group in web.SiteGroups) 
          {
            if (String.Equals(group.Name, name, StringComparison.InvariantCultureIgnoreCase)) 
            {
              return group;
            }
        }
         return null;
       }

        private static SPUser getUser(string name,SPWeb web)
        {
          foreach (SPUser user in web.SiteUsers) {
            if (String.Equals(user.LoginName, name, StringComparison.InvariantCultureIgnoreCase)) {
              return user;
            }
          }
          return null;      
        }

        }
}
